{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4d1b897a",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/jerryjliu/llama_index/blob/main/docs/examples/llm/Ollama.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2e33dced-e587-4397-81b3-d6606aa1738a",
   "metadata": {},
   "source": [
    "# Ollama - Llama 2 7B"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5863dde9-84a0-4c33-ad52-cc767442f63f",
   "metadata": {},
   "source": [
    "## Setup\n",
    "First, follow the [readme](https://github.com/jmorganca/ollama) to set up and run a local Ollama instance.\n",
    "\n",
    "When the Ollama app is running on your local machine:\n",
    "- All of your local models are automatically served on localhost:11434\n",
    "- Select your model when setting llm = Ollama(..., model=\"<model family>:<version>\")\n",
    "- Increase defaullt timeout (30 seconds) if needed setting Ollama(..., request_timeout=300.0)\n",
    "- If you set llm = Ollama(..., model=\"<model family\") without a version it will simply look for latest"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "833bdb2b",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4816bcb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-ollama"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bbbc106",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad297f19-998f-4485-aa2f-d67020058b7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.ollama import Ollama"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "152ced37-9a42-47be-9a39-4218521f5e72",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = Ollama(model=\"llama2\", request_timeout=30.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d61b10bb-e911-47fb-8e84-19828cf224be",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.complete(\"Who is Paul Graham?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bd14f4e-c245-4384-a471-97e4ddfcb40e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Paul Graham is a well-known entrepreneur, investor, and writer who has made significant contributions to the startup world.➖\n",
      "\n",
      "Here are some key facts about Paul Graham:\n",
      "\n",
      "1. Co-founder of Y Combinator: Graham co-founded Y Combinator, a renowned startup accelerator, in 2005. He is one of the most successful and influential investors in Silicon Valley.➖\n",
      "\n",
      "2. Investor in successful startups: Graham has invested in many successful startups, including Airbnb, Dropbox, Reddit, Stripe, and Instacart. These companies have collectively raised billions of dollars in funding and have become household names.➖\n",
      "\n",
      "3. Writer and blogger: Graham is also a prolific writer and blogger. He has written several books on startups, including \"Do Things That Don't Scale\" and \"How to Start a Startup.\" His blog, paulgraham.com, is popular among entrepreneurs and investors.➖\n",
      "\n",
      "4. Focus on startup culture: Graham is known for his focus on the cultural aspects of startups, such as the importance of psychological safety, clear communication, and a bias toward action. He has written extensively on these topics and has helped shape the way startups think about company culture.➖\n",
      "\n",
      "5. Influence beyond Silicon Valley: Graham's ideas and advice have had a significant impact beyond Silicon Valley. Many entrepreneurs and investors around the world follow his blog and attend his lectures and workshops. He has become a prominent voice in the global startup community.➖\n",
      "\n",
      "6. Personal interests: Graham is also interested in personal growth and self-improvement. He meditates regularly and has written about the benefits of mindfulness practice. He is also an avid reader and enjoys learning new things.➖\n",
      "\n",
      "7. Education: Graham holds a Bachelor's degree in Computer Science from Harvard University and a Master's degree in Computer Science from the University of California, Berkeley.➖\n",
      "\n",
      "8. Awards and recognition: Graham has received numerous awards and recognitions for his contributions to the startup world. He was named one of the 100 most influential people in the world by Time magazine in 2013.➖\n",
      "\n",
      "9. Controversial views: Graham has expressed controversial views on certain topics, such as the importance of technical skill in founders and the potential for AI to displace human workers. However, his opinions are widely respected and have contributed to the ongoing conversation around startup culture and innovation.➖\n",
      "\n",
      "10. Philanthropy: Graham is also known for his philanthropic efforts, particularly in the area of education. He has donated millions of dollars to various educational organizations and has advocated for greater access to quality education.➖\n",
      "\n",
      "Overall, Paul Graham is a highly respected figure in the startup world, known for his innovative approach to entrepreneurship, investing, and company culture. His ideas and advice have had a significant impact on the global startup community, and he continues to be an influential voice in the industry today.\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3ba9503c-b440-43c6-a50c-676c79993813",
   "metadata": {},
   "source": [
    "#### Call `chat` with a list of messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee8a4a55-5680-4dc6-a44c-fc8ad7892f80",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=\"system\", content=\"You are a pirate with a colorful personality\"\n",
    "    ),\n",
    "    ChatMessage(role=\"user\", content=\"What is your name\"),\n",
    "]\n",
    "resp = llm.chat(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a9bfe53-d15b-4e75-9d91-8c5d024f4eda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant:  ARRGH! Me hearty! *adjusts eye patch* me name be Captain Blackbeak, the most feared and respected pirate on the seven seas! *winks* What be bringin' ye to these waters, matey?\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "25ad1b00-28fc-4bcd-96c4-d5b35605721a",
   "metadata": {},
   "source": [
    "### Streaming"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "13c641fa-345a-4dce-87c5-ab1f6dcf4757",
   "metadata": {},
   "source": [
    "Using `stream_complete` endpoint "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06da1ef1-2f6b-497c-847b-62dd2df11491",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = llm.stream_complete(\"Who is Paul Graham?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b851def-5160-46e5-a30c-5a3ef2356b79",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Paul Graham is a well-known entrepreneur, investor, and writer who has been involved in the startup community for several decades. Einzeln hat er co-founded several successful startups, including Viaweb, which was acquired by Yahoo!, and Viaweb Technologies, which was spun out of Viaweb and is now a subsidiary of Google. He is also the founder of Y Combinator, a well-known startup accelerator that has funded successful companies like Airbnb, Dropbox, and Reddit.\n",
      "\n",
      "Graham is known for his essays on startups, entrepreneurship, and the tech industry, which have been widely read and discussed within the startup community. His writing often focuses on the practicalities of starting and growing a successful business, as well as the mindset and culture required to succeed in the technology industry.\n",
      "\n",
      "Some of his notable essays include:\n",
      "\n",
      "* \"How to Start a Startup\" - This essay provides practical advice for entrepreneurs looking to start a new business, including how to identify a market need, build a team, and raise capital.\n",
      "* \"The Three Faces of the Entrepreneur\" - In this essay, Graham identifies three types of entrepreneurs: the hobbyist, the technologist, and the salesperson. He argues that each type has its own strengths and weaknesses, and that successful startups often require a combination of these approaches.\n",
      "* \"The Paradox of Choice\" - In this essay, Graham explores the idea that too much choice can actually be harmful to entrepreneurs and startups. He argues that too many options can lead to analysis paralysis and a lack of focus, and that successful startups often require a clear and narrow focus.\n",
      "* \"The End of the Beginning\" - In this essay, Graham reflects on the changes he has seen in the startup ecosystem over the years, including the rise of accelerators, the importance of network effects, and the increasing emphasis on diversity and inclusion.\n",
      "\n",
      "Overall, Paul Graham is a respected figure within the startup community, known for his practical advice, insightful observations, and commitment to supporting innovative companies."
     ]
    }
   ],
   "source": [
    "for r in response:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ca52051d-6b28-49d7-98f5-82e266a1c7a6",
   "metadata": {},
   "source": [
    "Using `stream_chat` endpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe553190-52a9-436d-84ae-4dd99a1808f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=\"system\", content=\"You are a pirate with a colorful personality\"\n",
    "    ),\n",
    "    ChatMessage(role=\"user\", content=\"What is your name\"),\n",
    "]\n",
    "resp = llm.stream_chat(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "154c503c-f893-4b6b-8a65-a9a27b636046",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Shiver me timbers! Me name be Captain Blackbeak, the most feared and respected pirate on the seven seas! *adjusts eye patch* What be bringin' ye to these waters, matey? Are ye lookin' for a life of adventure and treasure? Or maybe just want to hear some tales of me exploits? Arrrr!"
     ]
    }
   ],
   "source": [
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
